//
//  CourseAudioVideoController.m
//  TrainTree
//
//  Created by wanghui on 2017/9/15.
//  Copyright © 2017年 YouYeShu. All rights reserved.
//

#import "CourseAudioVideoController.h"
#import "AudioVideoIntroduceCell.h"
#import "AudioVideoFileCell.h"
#import "AudioVideoListCell.h"
#import "CourseRequestManager.h"
#import "AudioVideoModel.h"
#import "ToolModel.h"
#import <AVKit/AVKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import "LRLVideoPlayerItem.h"
#import "LRLVideoPlayerView.h"
#import "QuickLookFileController.h"

#import "CLPlayerView.h"

@interface CourseAudioVideoController ()<UITableViewDelegate,UITableViewDataSource,LRLAVPlayDelegate,QuickLookDelegate>
{

    AudioVideoModel *_mainModel;
    ToolModel       *_toolModel;
    NSString        *_tempUrl;

}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (copy, nonatomic)NSString *videoUrl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topToVideoConstraint;
/**工具array*/
@property (strong,nonatomic)NSArray *toolArray;
 
@property (nonatomic, strong) LRLVideoPlayerView * player;
//------------------------分界线--------------------------
@property(strong, nonatomic) CLPlayerView *playerView;

@end

@implementation CourseAudioVideoController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
 
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTableView];
    self.topToVideoConstraint.constant = 212.0f / 375.0f * ScreenWidth + 20;
    [self requestDataWithPointId:self.pointId];

}


- (void)createTableView
{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"AudioVideoIntroduceCell" bundle:nil] forCellReuseIdentifier:@"AudioVideoIntroduceCell"];

    [self.tableView registerNib:[UINib nibWithNibName:@"AudioVideoFileCell" bundle:nil] forCellReuseIdentifier:@"AudioVideoFileCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"AudioVideoListCell" bundle:nil] forCellReuseIdentifier:@"AudioVideoListCell"];
}

- (void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
    [self.player releasePlayer];
    [self.player removeFromSuperview];
    self.player = nil;
}
 
#pragma  mark - 每次创建之前都先销毁。
// 暂时注释
- (void)createTopVideoView:(NSString *)url
{
    WeakSelf(ws);
//    [_playerView destroyPlayer];
//    CLPlayerView *playerView = [[CLPlayerView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 212.0f / 375.0f * ScreenWidth + 20)];
//    _playerView = playerView;
//    [self.view addSubview:_playerView];
//        //视频地址
//    _playerView.url = [NSURL URLWithString:url];
//    _playerView.fullStatusBarHidden = NO;
//        //播放
////    [_playerView playVideo];
//        //返回按钮点击事件回调
//    [_playerView backButton:^(UIButton *button) {
//
//        [ws.navigationController popViewControllerAnimated:YES];
//        [_playerView destroyPlayer];
//        _playerView = nil;
//    }];
//        //播放完成回调
//    [_playerView endPlay:^{
//            //销毁播放器
////        [_playerView destroyPlayer];
////        _playerView = nil;
//
//        NSLog(@"播放完成");
//    }];
//-------------------------------------------------------------------------
    [_playerView playVideo];
 
    [self.player releasePlayer];
    [self.player removeFromSuperview];
    self.player = nil;

    LRLVideoPlayerItem *playItem = [[LRLVideoPlayerItem alloc] init];
    playItem.videoUrlStr = url;
        //, item2, item3, item4
    self.player = [LRLVideoPlayerView avplayerViewWithPlayItems:@[playItem] andInitialHeight:212.0f / 375.0f * ScreenWidth + 20 andSuperView:self.view];

    self.player.backPlayMode = YES;
    self.player.delegate = self;
    [self.view addSubview:self.player];

        //播放器的外层UI封装部分依赖 Masonry 第三方库
    [self.player setPositionWithPortraitBlock:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.view).with.offset(0);
        make.left.equalTo(ws.view);
        make.right.equalTo(ws.view);
            //添加竖屏时的限制, 这条也是固定的, 因为: _videoHeight 是float* 类型, 我可以通过它, 动态改视频播放器的高度;
//        make.height.equalTo(@(*(ws.player.videoHeight)));
        make.height.equalTo(@(212.0f / 375.0f * ScreenWidth + 20));
    } andLandscapeBlock:^(MASConstraintMaker *make) {
        make.width.equalTo(@(SCREEN_HEIGHT));
        make.height.equalTo(@(SCREEN_WIDTH));
        make.center.equalTo(ws.view);

    }];

    [self.player prepare];

}
- (void)requestDataWithPointId:(NSString *)pointId
{
    WeakSelf(ws);
    [CourseRequestManager requestAudioVideoWithLessonId:pointId reponseBlock:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
        if (JSONData) {
            _mainModel = [AudioVideoModel mj_objectWithKeyValues:JSONData[@"d"]];
            ws.toolArray = JSONData[@"d"][@"tools"];
//            _toolModel = [ToolModel mj_objectWithKeyValues:JSONData[@"d"][@"tools"]];
            ws.videoUrl = _mainModel.pointVideoUrl;
            [ws.tableView reloadData];
            [ws createTopVideoView:ws.videoUrl];
            [CountVideo shareCountVideo].pointId = pointId;

            [self.view configResponseReveal:ResponsePageHome hasData:JSONData netError:JSONData reloadBlock:^(id sender) {
                [ws requestDataWithPointId:pointId];
            }];
        }
    }];
}
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return self.toolArray.count;
    }else{
       return  _mainModel.points.count;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
            return  [tableView fd_heightForCellWithIdentifier:@"AudioVideoIntroduceCell" configuration:^(id cell) {
                    // 将文字传入，自动计算cell高度
                AudioVideoIntroduceCell *cc = (AudioVideoIntroduceCell *)cell;
                cc.introduceLabel.text = _mainModel.pointDesc;

            }];

    }else if (indexPath.section == 1) {
        return 64;
    }else{
        return 82;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AudioVideoIntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AudioVideoIntroduceCell"];

        [cell configWith:_mainModel];
        return cell;
    }else if (indexPath.section == 1) {
        AudioVideoFileCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AudioVideoFileCell"];
        ToolModel *model = [ToolModel mj_objectWithKeyValues: self.toolArray[indexPath.row]];
        cell.delegate = self;
        [cell configWithModel:model];

        return cell;
    }else{
        AudioVideoListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AudioVideoListCell"];
        [cell configWithPointModel:_mainModel.points[indexPath.row]];
        return cell;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) {
//        AudioVideoIntroduceCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        cell.introduceLabel.numberOfLines = 20;
//        [tableView reloadData];
    } else if (indexPath.section == 1){
        // 下载

    } else {
        // 点击一条播放 先销毁视频播放
//        [self.player releasePlayer];
        id isAudio = [USERDEFAULT objectForKey:@"isAudio"];
        if([isAudio boolValue]) {// 音频状态下

        }else{

        }

        [self.player pause];

        PointModel *model = _mainModel.points[indexPath.row];
        CourseAudioVideoController *newMediaVc = [[CourseAudioVideoController alloc]init];
        newMediaVc.pointId = model.pointId;
        [_playerView pausePlay];
        [self.navigationController pushViewController:newMediaVc animated:YES];
    }
}

- (void)quickLookFile:(NSString *)filePath
{
    QuickLookFileController *quickLookVc = [[QuickLookFileController alloc]init];
    quickLookVc.filePath = filePath;
    self.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:quickLookVc animated:YES];

}

- (NSArray *)toolArray
{
    return _toolArray ?: (_toolArray = [NSArray array]);
}
#pragma mark - 关闭设备自动旋转, 然后手动监测设备旋转方向来旋转avplayerView
-(BOOL)shouldAutorotate{
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
